﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LDSP.BRL;
using System.Data;
using System.Text.RegularExpressions;
using ImplementationInitialization.Constants;

namespace ImplementationInitialization
{
    public class FinalCodificationImport : FinalImport
    {
        protected override void Import(string filename, System.Data.DataTable dt, int catalogID, string sheetName)
        {
            IDictionary<string, Codification> codDic = BaseDataInitial.GetExistedCodification();
            IDictionary<string, Catalog> catalogDic = BaseDataInitial.GetCatalogs();
            foreach (DataRow row in dt.Rows)
            {
                Codification cod = null;

                string name = row.ItemArray.Length > 1 && row[1] != null ? row[1].ToString() : string.Empty;
                name = GetChineseName(name);

                try
                {
                    Logger.WriteLog("====Begin Import Codification : " + name);

                    if (codDic.ContainsKey(name))
                    {//Update codification.
                        cod = codDic[name];
                        SetCodification(cod, catalogID, row, name);

                        cod.Update();

                        WriteImportItemResult(name, filename, sheetName, "更新", true);
                    }
                    else
                    {//Add codification.
                        cod = new Codification();
                        SetCodification(cod, catalogID, row, name);
                        cod.DocType = DocType.法律法规;
                        cod.UploadDT = DateTime.Now;

                        //Just mark newly added
                        cod.Comment1 = DateTime.Now.ToString();

                        cod.Add();

                        //加入到缓存.
                        BaseDataInitial.Add(codDic, cod);
                        _newCodifications.Add(cod);

                        WriteImportItemResult(name, filename, sheetName, "添加", true);
                    }
                }
                catch (Exception ex)
                {
                    string message = "Error import : " + "File Name : " + filename + " Codification : " + cod.Name
                        + "\n" + "Message : " + ex.Message;
                    Logger.WriteLog(message);

                    WriteImportItemResult(name, filename, sheetName, message, false);
                }

                Logger.WriteLog("====End Import Codification : " + name);
            }
        }

        protected override string AnalyseCodName(string fileName)
        {
            //string codName = fileName.IndexOf(".") > -1 ? fileName.Substring(0, fileName.IndexOf(".")) : fileName;

            ////最后一个下划线后面的是日期，其他是法规名。
            //if (fileName.Contains("_"))
            //{
            //    codName = fileName.Substring(0, fileName.LastIndexOf("_"));
            //}

            //return codName;
            return base.AnalyseCodName(fileName);
        }

        protected override IList<string> GetDisableList(Codification cod)
        {
            List<string> list = new List<string>();

            string str = _invalidList[cod];
            int start = str.IndexOf("《");
            int end = str.IndexOf("》");
            while (!string.IsNullOrEmpty(str) && start > -1 && end > -1)
            {
                list.Add(str.Substring(start + 1, end - start - 1));

                str = str.Substring(end + 1);
                start = str.IndexOf("《");
                end = str.IndexOf("》");
            }

            return list;
        }

        protected override void WriteImportAttachmentResult(string fileName, string message, bool success)
        {
            ImportResult.AddAttachmentResult(fileName, DocType.法律法规, message, success);
        }

        protected override void WriteImportItemResult(string codName, string excel, string sheet, string message, bool success)
        {
            ImportResult.AddItemResult(excel, DocType.法律法规, sheet, codName, message, success);
        }

        private void SetCodification(Codification cod, int catalogID, DataRow row, string name)
        {
            string referenceNumber = string.Empty;

            int i_category = 0;
            int i_organizaiton = 2;
            int i_reference_numbr = 3;
            int i_issue_date = 4;
            int i_implementation_date = 5;
            int i_summary = 6;
            int i_key_items = 7;
            int i_implementation_methods = 8;
            int i_invalid_list = 9;

            //类别
            cod.CategoryID = row[i_category] != null && _categoryDic.ContainsKey(row[i_category].ToString()) ? _categoryDic[row[i_category].ToString()].ID : 0;

            //法律法规名称
            cod.Name = name;

            //发布机构
            cod.Organization = row[i_organizaiton] != null ? row[i_organizaiton].ToString() : string.Empty;

            //发布文号
            referenceNumber = row[i_reference_numbr] != null ? row[i_reference_numbr].ToString() : string.Empty;
            cod.ReferenceNumber = referenceNumber;

            //发布日期
            DateTime releaseDT = DateTime.MinValue;
            if (row[i_issue_date] != null && DateTime.TryParse(row[i_issue_date].ToString(), out releaseDT))
            {
                releaseDT = DateTime.Parse(row[i_issue_date].ToString());
            }
            if (releaseDT != DateTime.MinValue)
            {
                cod.ReleaseDT = releaseDT;
            }

            //实施日期
            DateTime implementDT = DateTime.MinValue;
            if (row[i_implementation_date] != null && DateTime.TryParse(row[i_implementation_date].ToString(), out implementDT))
            {
                implementDT = DateTime.Parse(row[i_implementation_date].ToString());
            }
            if (implementDT != DateTime.MinValue)
            {
                cod.ImplementDT = implementDT;
            }

            cod.CatalogID = catalogID;

            //法规概述
            cod.Summary = row[i_summary] != null ? row[i_summary].ToString() : string.Empty;

            //关键条款
            cod.KeyItems = row[i_key_items] != null ? row[i_key_items].ToString() : string.Empty;

            //实施措施
            cod.Action = row[i_implementation_methods] != null ? row[i_implementation_methods].ToString() : string.Empty;

            //废止，修改的标准
            _invalidList.Add(cod, row[i_invalid_list] != null ? row[i_invalid_list].ToString() : string.Empty);
        }
    }
}
